"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const auth_1 = require("../middleware/auth");
const router = (0, express_1.Router)();
// 确保上传目录存在
const uploadDir = 'uploads/images';
if (!fs_1.default.existsSync(uploadDir)) {
    fs_1.default.mkdirSync(uploadDir, { recursive: true });
}
// 配置multer
const storage = multer_1.default.diskStorage({
    destination: (req, file, cb) => {
        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, file.fieldname + '-' + uniqueSuffix + path_1.default.extname(file.originalname));
    }
});
const fileFilter = (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
        cb(null, true);
    }
    else {
        cb(new Error('只能上传图片文件'), false);
    }
};
const upload = (0, multer_1.default)({
    storage,
    fileFilter,
    limits: {
        fileSize: 5 * 1024 * 1024 // 5MB
    }
});
// 图片上传路由
router.post('/image', auth_1.authMiddleware, upload.single('image'), (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({
                success: false,
                message: '没有上传文件'
            });
        }
        const imageUrl = `/uploads/images/${req.file.filename}`;
        res.json({
            success: true,
            message: '图片上传成功',
            data: {
                url: imageUrl,
                filename: req.file.filename,
                size: req.file.size
            }
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '图片上传失败',
            error: error.message
        });
    }
});
// 静态文件服务
router.use('/images', (req, res, next) => {
    const filename = req.path.substring(1); // 移除开头的 '/'
    const imagePath = path_1.default.join(process.cwd(), uploadDir, filename);
    if (fs_1.default.existsSync(imagePath)) {
        res.sendFile(imagePath);
    }
    else {
        res.status(404).json({
            success: false,
            message: '图片不存在'
        });
    }
});
exports.default = router;
